package com.czk.utils;

import com.czk.pojo.Invocation;
import com.czk.pojo.URL;
import com.czk.register.ZookeeperRegister;
import com.czk.server.NettyProtocol;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 动态代理方法
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/20 11:09
 */
public class ProxyFactory {
    public static <T> T getProxy(Class<T> interfaceClass) {
        // 动态代理
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method.getName());
                // 拿到url
                List<URL> urls = ZookeeperRegister.get(interfaceClass.getName());
                // 目前只有一个
                URL url = urls.get(0);
                // 构建请求
                Invocation invocation = new Invocation(interfaceClass.getCanonicalName(), method.getName(), method.getParameterTypes(), args);
                // 发送
                NettyProtocol nettyProtocol = new NettyProtocol();
                Object send = nettyProtocol.send(url, invocation);
                return send;
            }
        });
    }
}
